import 'package:edu/pages/common/empty_content_widget.dart';
import 'package:edu/pages/main_tab/edu/edu_course/edu_course_page_logic.dart';
import 'package:edu/pages/main_tab/edu/edu_course/edu_course_tab/edu_course_tab_widget.dart';
import 'package:edu/pages/main_tab/edu/edu_course/edu_course_tab/video_play/edu_course_video_play_widget.dart';
import 'package:edu/utils/account_info.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';

class EduCoursePage extends StatefulWidget {
  const EduCoursePage({super.key});

  @override
  State<EduCoursePage> createState() => _EduCoursePageState();
}

class _EduCoursePageState extends State<EduCoursePage>
    with WidgetsBindingObserver {
  DateTime? _start;

  @override
  void initState() {
    super.initState();
    context.read<EduCoursePageLogic>().init();

    WidgetsBinding.instance.addObserver(this);
    _start = DateTime.now();
  }

  @override
  void dispose() {
    super.dispose();
    if (_start != null) {
      final now = DateTime.now();
      final duration = now.difference(_start!);
      WidgetsBinding.instance.addPostFrameCallback((_) {
        AccountInfo.shared.addEduTimeInSeconds(duration.inSeconds);
      });
      _start = null;
    }
  }

  // 监听app生命周期
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      if (_start != null) {
        final now = DateTime.now();
        final duration = now.difference(_start!);
        AccountInfo.shared.addEduTimeInSeconds(duration.inSeconds);
        _start = null;
      }
    } else if (state == AppLifecycleState.resumed) {
      _start = DateTime.now();
    } else if (state == AppLifecycleState.detached) {
      if (_start != null) {
        final now = DateTime.now();
        final duration = now.difference(_start!);
        AccountInfo.shared.addEduTimeInSeconds(duration.inSeconds);
        _start = null;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: _buildMainBody(context),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return PreferredSize(
      preferredSize: Size.zero,
      child: AppBar(
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
      ),
    );
  }

  Widget _buildMainBody(BuildContext context) {
    return SafeArea(
      child: Column(
        children: [
          _buildCoursePlayWidget(context),
          _buildCourseContentWidget(context),
        ],
      ),
    );
  }

  // 课程播放组件
  Widget _buildCoursePlayWidget(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    final height = width * 9.0 / 16.0;
    return Stack(
      children: [
        Container(
          width: width,
          height: height,
          color: Colors.black,
          child: ChangeNotifierProvider(
            create: (_) => context.read<EduCoursePageLogic>().videoPlayLogic,
            child: const EduCourseVideoPlayWidget(),
          ),
        ),
        Positioned(
          top: 0,
          left: 0,
          child: IconButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            icon: const Icon(
              Icons.arrow_back_ios_new_sharp,
              color: Colors.white,
            ),
          ),
        ),
        Positioned(
          top: 0,
          right: 0,
          child: IconButton(
            onPressed: () {
              context.read<EduCoursePageLogic>().toggleFavorite();
            },
            padding: EdgeInsets.zero,
            icon: Selector<EduCoursePageLogic, bool>(
              selector: (context, logic) => logic.isMyFavorite,
              builder: (context, v, child) {
                if (v) {
                  return const Icon(
                    Icons.favorite,
                    color: Colors.white,
                    size: 26,
                  );
                } else {
                  return const Icon(
                    Icons.favorite_outline,
                    color: Colors.white,
                    size: 26,
                  );
                }
              },
            ),
          ),
        ),
      ],
    );
  }

  // 课程tab组件(课程目录, 课程简介, 课程评价)
  Widget _buildCourseContentWidget(BuildContext context) {
    return Selector<EduCoursePageLogic, bool>(
      selector: (context, logic) => logic.isContentEmpty,
      builder: (context, v, child) {
        if (v) {
          return Selector<EduCoursePageLogic, Tuple2<bool, bool>>(
            selector: (context, logic) => Tuple2(logic.loading, logic.error),
            builder: (context, v, child) {
              return Expanded(
                child: EmptyContentWidget(
                  isLoading: v.item1,
                  isError: v.item2,
                  reloadAction: () {
                    context.read<EduCoursePageLogic>().loadCourseDetail();
                  },
                ),
              );
            },
          );
        } else {
          return const EduCourseTabWidget();
        }
      },
    );
  }
}
